# -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 11:16:13 2019

@author: Dawud

@e-mail: Dawudcn@icloud.com
"""
import random
import sys
arcpy_path = [r'C:\Python27\ArcGIS10.6\Lib\site-packages',
              r'C:\Program Files (x86)\ArcGIS\Desktop10.6\arcpy',
              r'C:\Program Files (x86)\ArcGIS\Desktop10.6\bin',
              r'C:\Program Files (x86)\ArcGIS\Desktop10.6\ArcToolbox\Scripts']
sys.path.extend(arcpy_path)
import datetime
import arcpy

#print u"请输入相关参数，若无字段请留空"
parms = {}
parms["cg"] = raw_input("1. Please input floor height field:")
parms["cs"] = raw_input("2. Please input floors field:")
parms["zg"] = raw_input("3. Please input total height field:")

startTime=datetime.datetime.now()
print u"生成进程转换"

#单层文件的工作目录
InputSpace= "data"
#结果文件的存放目录
OutputSpace= "buildings\\"
#坐标系
sr = arcpy.SpatialReference(4326)
#当前序列
num = 0
#设置工作空间
arcpy.env.workspace=InputSpace
#单层转多层
def one2N(shp):
    #列出所有字段
    fieldObjList = arcpy.ListFields(shp)
    fieldArr = []
    # 获取当前 SHP 属性字段列表
    for f in fieldObjList:
        fieldArr.append(f.name)
    # 核心字段名
    coreFieldlist = [
            {"fieldName": "cg",
             "fieldAlias": u"层高"},
            {"fieldName": "cs",
             "fieldAlias": u"层数"},
            {"fieldName": "zg",
             "fieldAlias": u"总高度"}]
    # 如果不存在字段则生成
    for c in coreFieldlist:
        fieldPrecision = 99
        if not c["fieldName"] in fieldArr:
            fieldName = c["fieldName"]
            fieldAlias = c["fieldAlias"]
            arcpy.AddField_management(shp, fieldName, "LONG", fieldPrecision, "", "",
            fieldAlias, "NULLABLE")
            print u"已生成" + fieldName + u"字段"
        arcpy.AddField_management(newShp, c["fieldName"], "LONG", fieldPrecision, "", "",
            c["fieldAlias"], "NULLABLE")
    # 遍历每个要素
    cursor = arcpy.UpdateCursor(shp)
    # 原始 SHP 总要素数量
    features_cnt = arcpy.GetCount_management(shp).getOutput(0)
    print u"要素总数：{0}".format(features_cnt)
    # 原始 SHP 要素执行次数
    feature_index = 1
    for row in cursor:
        # 设置核心三参数
        parms["zg"] = parms["zg"] if(parms["zg"]) else "zg"
        parms["cg"] = parms["cg"] if(parms["cg"]) else "cg"
        parms["cs"] = parms["cs"] if(parms["cs"]) else "cs"
        _name = row.getValue('name')
        # 楼栋总高度
        _zg = row.getValue(parms["zg"]) if(row.getValue(parms["zg"])) else 0
        # 楼栋层高
        _cg = row.getValue(parms["cg"]) if(row.getValue(parms["cg"])) else 3
        # 楼栋层数
        _cs = int(row.getValue(parms["cs"])) if(row.getValue(parms["cs"])) else int(_zg / _cg)
        # 更新 总高度 字段属性
        row.setValue("zg", _zg)
        # 更新 层高 字段属性
        row.setValue("cg", _cg)
        # 更新 层数 字段属性
        row.setValue("cs", _cs)
        # 更新此行数据
        cursor.updateRow(row)
        print u"【{0} 总高度 {1} 米，层高 {2} 米，楼高 {3} 层】".format(_name, _zg, _cg, _cs)
        # 根据层数复制生成要素
        arcpy.AddField_management(newShp, "name", "TEXT", fieldPrecision, "", "",
            "名称", "NULLABLE")
        # 定义新增 SHP 插入游标
        insert_cursor = arcpy.InsertCursor(newShp)
        # 对原有的每个要素进行处理，根据层数新增SHP
        for x in range(0, _cs):
            rowX = row 
            rowX.setValue("name", _name)
            rowX.setValue("cg", _cg)
            rowX.setValue("zg", (x+1) * _cg)
            rowX.setValue("cs", (x+1))
            insert_cursor.insertRow(rowX)
            print u"总体进度 {0} / {1} ，正在为 {2} 要素生成楼栋体，当前楼栋进度：{3} / {4} ".format(feature_index, features_cnt, _name, x+1, _cs)  
        feature_index = feature_index + 1
        return

#获取总图层数
totalNum = len(arcpy.ListFiles("*.shp"))
#遍历所有输入图层
for in_features in arcpy.ListFiles("*.shp"):
    # 根据输入SHP新建输出SHP
    global newShp
    newShp = arcpy.CreateFeatureclass_management(OutputSpace, str(random.randint(1,100)), "POLYGON", "", "", "", sr)
    one2N(in_features)
    # 将成果转为 JSON 
    arcpy.FeaturesToJSON_conversion(newShp, OutputSpace + "output.json", "FORMATTED")
 
 
endTime=datetime.datetime.now()
exeTime=(endTime-startTime).seconds
print u"已完成，总耗时：",exeTime,u"秒"